<template>
  <div>
    <el-form @submit.native.prevent>
      <el-form-item label="引导语" :rules="{ required: true }">
        <el-radio-group v-model="guideIndex">
          <el-radio :label="index" :key="index" v-for="(str, index) of guideArr">{{ str }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <div class="wrapper" v-show="guideIndex">
      <div class="input-row">
        <el-form :inline="true" :model="formInline" @submit.native.prevent>
          <el-form-item label="标准名称">
            <el-input size="small" clearable v-model="formInline.name" @keyup.native.enter="handleFilter" />
          </el-form-item>
          <el-form-item label="标准编号">
            <el-input size="small" clearable v-model="formInline.code" @keyup.native.enter="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter" size="small">查询</el-button>
            <el-button @click="resetQuery" size="small">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        ref="tableRef"
        class="ins-table"
        max-height="500"
        @select="handleSelectRow"
        @select-all="handleSelectAll"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="标准名称"> </el-table-column>
        <el-table-column prop="code" width="200" label="标准编号"> </el-table-column>
      </el-table>

      <el-pagination
        v-if="total"
        layout="prev, pager, next"
        :page-size="10"
        :total="total"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { v4 as uuid } from 'uuid'
import { getStandardPage } from '@/api'
import { getLinkUrl } from '@/utils/helpers'

export default {
  name: 'TabPaneGuide',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    guideIndex(val, oldVal) {
      if (val === 0) {
        this.multipleSelection = []
        this.$refs.tableRef.clearSelection()
      }
      if (val && oldVal === 0) {
        this.resetQuery()
      }
    }
  },
  data() {
    return {
      loading: false,
      guideIndex: 0,
      total: 0,
      currentPage: 1,
      tableData: [],
      multipleSelection: [],
      formInline: {
        name: undefined,
        code: undefined
      }
    }
  },
  computed: {
    guideArr() {
      const str = this.multipleSelection.map((i) => i.code).join('、') || '……'
      return [
        '下列术语和定义适用于本文件。',
        `${str}界定的以及下列术语和定义适用于本文件。`,
        `${str}界定的以及下列术语和定义适用于本文件。为了便于使用，以下重复列出了${str}中的一些术语和定义。`,
        `${str}界定的术语和定义适用于本文件。`,
        `${str}界定的下列术语和定义适用于本文件，为了便于使用，以下重复列出${str}中的一些术语和定义。`
      ]
    }
  },
  methods: {
    setData({ guideIndex, selections }) {
      this.guideIndex = guideIndex
      this.multipleSelection = selections.map((item) => {
        const bizExtra = JSON.parse(item.bizExtra)
        return {
          docNo: bizExtra.docno,
          name: bizExtra.refname,
          id: bizExtra.standardId,
          mainContentId: bizExtra.mainContentId,
          classification: bizExtra.refclassification,
          version: bizExtra.refversion,
          code: bizExtra.refcode
        }
      })
      this.resetQuery()
    },
    getData() {
      return {
        guideIndex: this.guideIndex,
        selections: this.multipleSelection.map((item, index, arr) => {
          return {
            contentType: 'refdoc',
            contentNumber: null,
            linkUrl: getLinkUrl(item.mainContentId) || '',
            bizExtra: JSON.stringify({
              refname: item.name,
              standardId: item.id,
              mainContentId: item.mainContentId,
              refclassification: item.classification,
              refdate: '',
              refcode: item.code,
              refanchor: '', // TODO
              docno: item.docNo || '',
              refversion: item.version
            }),
            content: item.code,
            fullContent: item.code + (index === arr.length - 1 ? '' : '、'),
            dataId: uuid()
          }
        })
      }
    },
    resetQuery() {
      this.currentPage = 1
      this.formInline = {
        name: undefined,
        code: undefined
      }
      this.handleFilter()
    },
    handleSelectRow(selection, row) {
      if (selection.every((item) => item.id !== row.id) && this.multipleSelection.some((item) => item.id === row.id)) {
        this.multipleSelection = this.multipleSelection.filter((item) => item.id !== row.id)
      }
    },
    handleSelectAll(selection) {
      console.debug('handleSelectAll', selection)
      if (selection.length === 0) {
        this.tableData.forEach((row) => {
          this.multipleSelection = this.multipleSelection.filter((item) => item.id !== row.id)
        })
      }
    },
    handleSelectionChange(arr) {
      arr.forEach((sel) => {
        if (this.multipleSelection.every((item) => item.id !== sel.id)) {
          this.multipleSelection.push(sel)
        }
      })
    },
    async handleFilter(e) {
      if (e) {
        this.currentPage = 1
      }
      const data = { ...this.formInline, pageSize: 10, pageNum: this.currentPage, fileProperty: '1' }
      this.loading = true
      const res = await getStandardPage(data)
      this.loading = false
      const { count, list, pageNum } = res
      this.total = count
      this.tableData = list
      this.currentPage = pageNum

      this.$nextTick(() => {
        this.tableData.forEach((row) => {
          if (this.multipleSelection.find((item) => item.id === row.id)) {
            this.$refs.tableRef.toggleRowSelection(row, true)
          }
        })
      })
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.handleFilter()
    }
  }
}
</script>

<style scoped>
::v-deep .el-radio-grou {
  width: 100%;
}
::v-deep .el-radio {
  display: block;
  margin: 10px 0;
  max-width: 100%;
  white-space: initial;
}
</style>
